package org.gap.wizards.state;

import java.util.HashMap;
import java.util.Map;

import org.gap.wizards.views.ViewPlatform;

public class TransitionTracker {
	private Map<TransitionState, Map<Condition, TransitionState>> transitions;
	private TransitionState currentState;

	public TransitionTracker() {
		transitions = new HashMap<TransitionState, Map<Condition, TransitionState>>();
	}

	public void setStart(TransitionState start) {
		start.enter();
		currentState = start;
	}

	public void addTransition(TransitionState fromState, Condition onKey, TransitionState toState) {
		if (!transitions.containsKey(fromState)) {
			HashMap<Condition, TransitionState> transitionTo = new HashMap<Condition, TransitionState>();
			transitions.put(fromState, transitionTo);
		}
		transitions.get(fromState).put(onKey, toState);
	}

	public void draw(ViewPlatform console) {
		currentState.draw(console);
		if (checkForTransition('\n')) {
			currentState.draw(console);
		}
	}

	public void acceptKey(char keyPress) {
		if (checkForTransition(keyPress)) {
			return;
		}
		currentState.acceptKey(keyPress);
	}

	private boolean checkForTransition(char keyPress) {
		Map<Condition, TransitionState> conditions = transitions.get(currentState);
		for (Condition each : conditions.keySet()) {
			if (each.isCondition(keyPress)) {
				currentState.exit();
				currentState = conditions.get(each);
				currentState.enter();
				return true;
			}
		}
		return false;
	}

	public boolean isEndState() {
		return !transitions.containsKey(currentState);
	}
}
